package com.portalEsporteClubeBahia.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.portalEsporteClubeBahia.app.ApplicationException;
import com.portalEsporteClubeBahia.app.bo.MediaBO;
import com.portalEsporteClubeBahia.app.vo.MediaVO;
import com.portalEsporteClubeBahia.app.vo.TypeMediaVO;

public class FindAllMediasAC extends HttpServlet {

	private static final long serialVersionUID = 8022328258260288800L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		JSONObject returning = new JSONObject();
		String status = "";
 		String message = "";
		JSONArray arrayData = new JSONArray();
		
		try {
			
			List<TypeMediaVO> listType = new MediaBO().findAllTypeMedia();
			JSONArray arrayTypeMedia = new JSONArray();
			
			if(listType.size()>0){
				
				for(TypeMediaVO type : listType){
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", type.getId());
					jsonObject.put("name", type.getName());
					arrayTypeMedia.add(jsonObject);
				}
				
			}
			
			List<MediaVO> list = new MediaBO().findAll();
			JSONArray arrayMedia = new JSONArray();
			
			if(list.size()>0){
				
				for(MediaVO media : list){
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("id", media.getId());
					jsonObject.put("typeID", media.getTypeMedia().getId());
					jsonObject.put("typeName", media.getTypeMedia().getName());
					jsonObject.put("title", media.getTitle());
					jsonObject.put("urlMedia", media.getUrlMedia());
					jsonObject.put("date", media.getDateFormat());
					jsonObject.put("shortContent", media.getShortContent());
					jsonObject.put("active", media.getActive());
					jsonObject.put("time", media.getTimeFormat());
					jsonObject.put("ranking", media.getRanking());
					arrayMedia.add(jsonObject);
				}
				
			}
			
			status =  "OK";
 			message = "";
 			
 			arrayData.add(arrayTypeMedia);
 			arrayData.add(arrayMedia);
			
		}catch (ApplicationException e) {
			status  =  "ERROR";
  			message = e.getMessage();
		}
		
		returning.put("status",status);
 		returning.put("message",message);
 		returning.put("data",arrayData);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(returning.toString());
		
	}

}
